<script lang="ts" setup>
  import { defineProps, ref, watch, defineEmits } from "vue"
    import { type FormInstance, ElMessage, ElMessageBox,type FormRules } from "element-plus"
  import { usePagination } from "@/hooks/usePagination"
  import handle from './components/handle.vue'

  const loading = ref<boolean>(false)
  const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
  const dialogVisible = ref<boolean>(false)
  const activeRow = ref<any>()

  interface Props {
    modelValue?: any,
    title?: string
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: ()=>([]),
    title: "",
  })

  const tableData = ref<any>(props.modelValue)
  const emit = defineEmits(['update:modelValue']);

  //关闭操作框
  const closeHandle = () => {
    dialogVisible.value = false
  }

  const handleAdd = () => {
    activeRow.value = null
    dialogVisible.value = true
  }

  const handleEdit = (row: any, index: number)=> {
    activeRow.value = row
    activeRow.value.index = index
    // 判断attachment的类型并正确处理
    if (row.attachment) {
      if (Array.isArray(row.attachment)) {
        // 如果已经是数组，直接使用
        activeRow.value.attachment = row.attachment
      } else if (typeof row.attachment === 'string') {
        try {
          // 尝试解析JSON字符串
          const parsed = JSON.parse(row.attachment)
          activeRow.value.attachment = Array.isArray(parsed) ? parsed : row.attachment.split(',')
        } catch (e) {
          // 如果JSON解析失败，则按照原来的方式用逗号分割
          activeRow.value.attachment = row.attachment.split(',')
        }
      } else {
        // 其他情况设为空数组
        activeRow.value.attachment = []
      }
    } else {
      activeRow.value.attachment = []
    }
    dialogVisible.value = true
}

  const handleDelete = (index: number) => {
    tableData.value.splice(index,1)
    emit('update:modelValue',tableData.value)
  }

  const successHandle = (row: any) => {
    const index = tableData.value.findIndex((item: any) => item.contractId === row.contractId)
    if (index !== -1) {
      tableData.value[index] = row
      tableData.value[index].attachment = row.attachment.join(',')
    } else {
      tableData.value.push(row)
    }

    dialogVisible.value = false
    emit('update:modelValue', tableData.value)
  }
  const handleDownload = (attachmentUrl: string) => {
  let urls: string[] = [];
  if (!attachmentUrl) {
    ElMessage({
      message: '没有可用的附件',
      type: 'warning',
    });
    return;
  }
  if (typeof attachmentUrl === 'string') {
    try {
      // 尝试解析为JSON数组
      const parsed = JSON.parse(attachmentUrl);
      if (Array.isArray(parsed)) {
        urls = parsed;
      } else if (typeof parsed === 'string') {
        urls = [parsed];
      }
    } catch (e) {
      // 不是JSON格式，按逗号分割
      urls = attachmentUrl.split(',');
    }
  } else if (Array.isArray(attachmentUrl)) {
    urls = attachmentUrl;
  }
  // 打开第一个附件
  if (urls.length && urls[0]) {
    window.open(urls[0], '_blank');
  } else {
    ElMessage({
      message: '没有可用的附件',
      type: 'warning',
    });
  }
};

  watch(
    () => props.modelValue,
    (newVal, oldVal) => {
      tableData.value = newVal
    }
  )
</script>

<template>
  <div class=" form-card-title-hr toolbar-wrapper center">
    <div v-if="props.title">{{props.title}}</div>
   <el-button type="primary" @click="handleAdd" v-permission="['prodetail-add']">新增</el-button>
  </div>

  <div v-loading="loading"  class="table-wrapper form-card-main">
    <el-table :data="tableData" >
      <el-table-column prop="name" label="合同名称"  />
      <el-table-column prop="startTime" label="开始日期" >
      </el-table-column>
      <el-table-column prop="endTime" label="结束日期"  />
      <el-table-column prop="requestPayNum" label="合同内请款次数"  />
      <el-table-column fixed="right" label="操作" width="150" >
        <template #default="scope">
          <el-button type="primary" text size="small" @click="handleDownload(scope.row.attachment)">查看附件</el-button>
          <el-button type="primary" text size="small" @click="handleEdit(scope.row, scope.$index)">修改</el-button>
          <el-button type="danger" text size="small" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <handle
    v-if="dialogVisible"
    :data="activeRow"
    @success="successHandle"
    @cancel="closeHandle"
    />
</template>

<style lang="scss" scoped>
  .center{
    align-items: center;
    gap:20px;
  }
</style>
